﻿using System;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Common.Exceptions;

namespace Fuse8.DomainFramework.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    public static class UnitOfWorkController<T> where T : class, IEntityObject, new()
    {
        /// <summary>
        /// 
        /// </summary>
        public static IUnitOfWork<T> GetCurrentUnitOfWork(bool throwException = true)
        {
            if (!throwException && !DependencyServiceLocator.Current.IsRegistered<IUnitOfWorkFactory<T>>())
            {
                return null;
            }
            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<T>>();

            if (factory == null)
            {
                throw new UnitOfWorkFactoryNotDefinedException();
            }

            var result = factory.Get(false);

            if (result == null)
            {
                throw new UnitOfWorkNotDefinedException();
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        public static void CallCloseToUnitOfWork()
        {
            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<T>>();

            if (factory == null)
            {
                throw new UnitOfWorkFactoryNotDefinedException();
            }

            factory.Close();
        }
    }
}
